package tenthwork.three;


/**
 * @author ：chenzikang
 * @date ： 2020/4/22
 */

class Producer extends Thread {
    private ShareArea shareObject;

    public Producer(ShareArea shareObject) {
        this.shareObject = shareObject;
    }

    @Override
    public void run() {

        for (int count = 0; count <= 10; count++) {
            try {
                Thread.sleep((int) (Math.random() * 500));
            } catch (InterruptedException e) {

            }
            //消费者把数字放进去
            shareObject.setSharedInt(count);


            System.out.println("生产" + count);
        }

    }
}





class Consumer extends Thread {

    private ShareArea sharedObject;

    // 通过构造方法配置name属性
    public Consumer(ShareArea shared) {
        sharedObject = shared;
    }

    @Override
    public void run() {
        int value;
        do {
            try {
                Thread.sleep((int) (Math.random() * 1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            value = sharedObject.getSharedInt();
            System.out.println("消费" + value);
        } while (value != 10);

    }

}



/**
 *    首先将sharedInt置为-1，writeable为true，不进入等待，存入新的sharedInt后进入等待。等消费者取出sharedInt后，将
 *  writeable反转，进入等待。生产者置数后等待，等生产者取出后
 *
 *
 */

class ShareArea {

    private int sharedInt = -1;
    private boolean writeable = true;

    public synchronized void setSharedInt(int value) {
        while (!writeable) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        //把value值存入shardInt
        sharedInt = value;

        //改变存储状态
        writeable = false;
        notify();

    }

    public synchronized int getSharedInt() {
        while (writeable) {
            try {
                wait();
            } catch (InterruptedException e) {

            }

        }
        writeable = true;

        notify();


        return sharedInt;
    }
}


public class SharedTest {
    public static void main(String args[]) {
        ShareArea shareArea = new ShareArea();
        Producer producer = new Producer(shareArea);
        Consumer consumer = new Consumer(shareArea);

        consumer.start();
        producer.start();

    }
}
